<template>
    <view class="container">
        <!-- 顶部导航栏 -->
        <view class="nav-bar">
            <view class="nav-back" @click="goBack">
                <text class="iconfont icon-back">&#xe679;</text>
            </view>
            <view class="nav-title">手写签名验证</view>
        </view>

        <!-- 主体内容区域 -->
        <view class="page-content">
            <!-- 签名区域 -->
            <view class="signature-wrapper">
                <view class="signature-tips">
                    <text class="tips-title">请在下方区域内签名</text>
                    <text class="tips-desc">请依次签写"{{expectedText}}"，当前请签写：{{currentChar}}</text>
                    <view class="progress-bar">
                        <view v-for="(char, index) in expectedTextArray" :key="index" class="progress-item"
                            :class="{'active': currentIndex === index, 'completed': index < currentIndex}">
                            <text>{{char}}</text>
                        </view>
                    </view>
                </view>

                <view class="signature-area" :style="{ height: signatureHeight + 'px' }">
                    <!-- 背景文字 -->
                    <view class="signature-bg" v-if="currentChar">
                        <text class="signature-text">{{currentChar}}</text>
                    </view>
                    <!-- 签名画布 -->
                    <canvas canvas-id="signatureCanvas" class="signature-canvas" @touchstart="handleTouchStart"
                        @touchmove="handleTouchMove" @touchend="handleTouchEnd" :disable-scroll="true"></canvas>

                    <!-- 参考线 -->
                    <view class="signature-line"></view>
                </view>

                <!-- 操作按钮 -->
                <view class="btn-group">
                    <view class="btn btn-clear" @click="clearSignature">
                        <text class="btn-icon">&#xe6a0;</text>
                        <text class="btn-text">重新签名</text>
                    </view>
                    <view class="btn btn-next" @click="nextCharacter" :class="{'btn-disabled': !hasSignature}"
                        v-if="!isLastChar">
                        <text class="btn-icon">&#xe65d;</text>
                        <text class="btn-text">下一个字</text>
                    </view>
                    <view class="btn btn-submit" @click="submitSignature" :class="{'btn-disabled': !hasSignature}"
                        v-if="isLastChar">
                        <text class="btn-icon">&#xe65d;</text>
                        <text class="btn-text">提交验证</text>
                    </view>
                </view>
            </view>

            <!-- 已完成的签名预览 -->
            <view class="completed-signatures" v-if="completedSignatures.length > 0">
                <view class="completed-title">已完成的签名</view>
                <view class="signature-preview">
                    <view class="preview-item" v-for="(item, index) in completedSignatures" :key="index">
                        <image :src="item.image" mode="aspectFit" class="preview-image"></image>
                        <text class="preview-text">{{item.char}}</text>
                    </view>
                </view>
            </view>

            <!-- 签名示例 -->
            <view class="example-section" v-if="showExample">
                <view class="example-title">
                    <text>签名示例</text>
                    <view class="example-close" @click="showExample = false">&#xe6a0;</view>
                </view>
                <image class="example-image" src="/static/signature_example.png" mode="aspectFit"></image>
            </view>

            <!-- 验证结果弹窗 -->
            <view class="result-modal" v-if="showResult">
                <view class="modal-mask" @click="closeResult"></view>
                <view class="modal-content">
                    <view class="modal-header">
                        <view class="modal-title">验证结果</view>
                        <view class="modal-close" @click="closeResult">&#xe6a0;</view>
                    </view>
                    <view class="modal-body">
                        <view class="result-icon" :class="{'success': verifySuccess, 'fail': !verifySuccess}">
                            <text v-if="verifySuccess">&#xe65d;</text>
                            <text v-else>&#xe64d;</text>
                        </view>
                        <view class="result-text">
                            <text class="result-status">{{verifySuccess ? '验证通过' : '验证失败'}}</text>
                            <text class="result-desc">{{verifySuccess ? '您的签名已通过验证' : '签名与预期不符，请重新签名'}}</text>
                        </view>
                        <view class="result-detail" v-if="recognizedText">
                            <text class="detail-label">识别结果：</text>
                            <text class="detail-value">{{recognizedText}}</text>
                        </view>
                        <view class="result-detail" v-if="similarityScore">
                            <text class="detail-label">相似度：</text>
                            <text class="detail-value">{{similarityScore}}%</text>
                        </view>
                        
                        <!-- 合并后的签名图片预览 -->
                        <view class="merged-signature" v-if="verifySuccess && mergedSignatureImage">
                            <text class="merged-title">合并签名</text>
                            <image :src="mergedSignatureImage" mode="widthFix" class="merged-image"></image>
                        </view>
                    </view>
                    <view class="modal-footer">
                        <view class="modal-btn" @click="closeResult">{{verifySuccess ? '完成' : '重新签名'}}</view>
                        <view class="modal-btn primary" v-if="verifySuccess" @click="confirmSignature">确认使用</view>
                    </view>
                </view>
            </view>

            <!-- 用于合并签名的隐藏画布 -->
            <canvas canvas-id="mergeCanvas" class="merge-canvas"></canvas>

            <!-- 加载提示 -->
            <grace-loading :loadingType="1" loadingText="正在验证签名..." v-if="loading"></grace-loading>
        </view>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                context: null,
                points: [],
                signText: '', // 背景显示的文本
                canvasWidth: 0,
                canvasHeight: 0,
                signatureHeight: 300, // 默认高度
                loading: false,
                showExample: false,
                showResult: false,
                verifySuccess: false,
                recognizedText: '',
                similarityScore: 0,
                hasSignature: false,
                lastPoint: null,
                strokeColor: '#000000',
                strokeWidth: 4,
                expectedText: '', // 预期的签名文本
                signatureImage: '',
                mergedSignatureImage: '', // 合并后的签名图片

                // 分步签名相关数据
                expectedTextArray: [], // 预期文本拆分为字符数组
                currentIndex: 0, // 当前签名的字符索引
                currentChar: '', // 当前需要签名的字符
                completedSignatures: [], // 已完成的签名数组
                allSignatureImages: [], // 所有签名图片的路径
                allSignatureBase64: [] // 所有签名图片的base64数据
            }
        },
        computed: {
            isLastChar() {
                return this.currentIndex === this.expectedTextArray.length - 1;
            }
        },
        onLoad(options) {
            // 获取预期签名文本
            if (options.text) {
                this.signText = decodeURIComponent(options.text);
                this.expectedText = this.signText;
            } else {
                this.signText = '大张伟';
                this.expectedText = '大张伟';
            }

            // 将预期文本拆分为字符数组
            this.expectedTextArray = this.expectedText.split('');
            this.currentChar = this.expectedTextArray[0];

            // 获取设备信息以适配不同屏幕
            const systemInfo = uni.getSystemInfoSync();
            // 放大签名区域高度，从原来的0.8倍屏幕宽度增加到1.0倍
            this.signatureHeight = systemInfo.windowWidth * 1.0;

            // 初始化画布
            this.$nextTick(() => {
                this.initCanvas();
            });
        },
        onReady() {
            // 在页面渲染完成后再次确保画布初始化
            this.initCanvas();
        },
        methods: {
            // 初始化画布
            initCanvas() {
                const query = uni.createSelectorQuery().in(this);
                query.select('.signature-canvas').boundingClientRect(data => {
                    if (data) {
                        this.canvasWidth = data.width;
                        this.canvasHeight = data.height;
                        
                        // 创建画布上下文
                        this.context = uni.createCanvasContext('signatureCanvas', this);
                        this.context.strokeStyle = this.strokeColor;
                        this.context.lineWidth = this.strokeWidth;
                        this.context.lineCap = 'round';
                        this.context.lineJoin = 'round';
                    }
                }).exec();
            },
            
            // 触摸开始事件
            handleTouchStart(e) {
                const touch = e.touches[0];
                const x = touch.x;
                const y = touch.y;
                
                this.lastPoint = { x, y };
                this.points = [{ x, y }]; // 重置点集合，只保留起始点
                this.hasSignature = true;
                
                // 开始新路径
                this.context.beginPath();
                this.context.moveTo(x, y);
                // 绘制一个小点，确保即使用户只点击一下也有标记
                this.context.arc(x, y, this.strokeWidth / 2, 0, 2 * Math.PI);
                this.context.fill();
                this.context.stroke();
                this.context.draw(true);
            },
            
            // 触摸移动事件
            handleTouchMove(e) {
                const touch = e.touches[0];
                const x = touch.x;
                const y = touch.y;
                
                // 如果没有上一个点，直接返回
                if (!this.lastPoint) {
                    this.lastPoint = { x, y };
                    return;
                }
                
                // 计算两点之间的距离
                const dx = x - this.lastPoint.x;
                const dy = y - this.lastPoint.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                // 如果距离太小，不处理以提高性能，但阈值降低以捕获更多点
                if (distance < 1) {
                    return;
                }
                
                // 保存当前点
                this.points.push({ x, y });
                
                // 使用贝塞尔曲线平滑连接点
                if (this.points.length > 2) {
                    // 获取前两个点
                    const p1 = this.points[this.points.length - 3];
                    const p2 = this.points[this.points.length - 2];
                    const p3 = this.points[this.points.length - 1];
                    
                    // 使用三次贝塞尔曲线连接点，使线条更平滑
                    this.context.beginPath();
                    this.context.moveTo(p1.x, p1.y);
                    
                    // 计算控制点
                    const cp1x = p1.x + (p2.x - p1.x) / 2;
                    const cp1y = p1.y + (p2.y - p1.y) / 2;
                    const cp2x = p2.x + (p3.x - p2.x) / 2;
                    const cp2y = p2.y + (p3.y - p2.y) / 2;
                    
                    // 绘制贝塞尔曲线
                    this.context.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, p3.x, p3.y);
                } else {
                    // 如果点数不足，使用简单的线段连接
                    this.context.beginPath();
                    this.context.moveTo(this.lastPoint.x, this.lastPoint.y);
                    this.context.lineTo(x, y);
                }
                
                this.context.stroke();
                this.context.draw(true);
                
                this.lastPoint = { x, y };
            },
            
            // 触摸结束事件
            handleTouchEnd() {
                if (this.points.length > 0) {
                    // 确保最后一笔也被绘制
                    if (this.points.length >= 2) {
                        const lastPoint = this.points[this.points.length - 1];
                        const prevPoint = this.points[this.points.length - 2];
                        
                        this.context.beginPath();
                        this.context.moveTo(prevPoint.x, prevPoint.y);
                        this.context.lineTo(lastPoint.x, lastPoint.y);
                        this.context.stroke();
                        this.context.draw(true);
                    }
                    
                    this.context.closePath();
                    this.lastPoint = null;
                }
            },

            // 清除签名
            clearSignature() {
                if (this.context) {
                    this.context.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
                    this.context.draw();
                    this.points = [];
                    this.hasSignature = false;
                    this.showResult = false;
                }
            },

            // 进入下一个字符的签名
            nextCharacter() {
                if (!this.hasSignature) {
                    uni.showToast({
                        title: '请先完成当前字的签名',
                        icon: 'none'
                    });
                    return;
                }

                // 保存当前字符的签名图片
                this.saveCurrentSignature();
            },

            // 保存当前签名
            saveCurrentSignature() {
                this.loading = true;

                // 将画布内容转为图片
                uni.canvasToTempFilePath({
                    canvasId: 'signatureCanvas',
                    fileType: 'jpg', // 使用JPG格式，更容易被OCR识别
                    quality: 0.8, // 降低质量以减小文件大小
                    // 设置更合适的尺寸，避免图片过大
                    width: this.canvasWidth,
                    height: this.canvasHeight,
                    destWidth: 150, // 进一步降低分辨率
                    destHeight: 150,
                    success: res => {
                        // 保存当前字符的签名
                        this.completedSignatures.push({
                            char: this.currentChar,
                            image: res.tempFilePath
                        });

                        // 保存图片路径
                        this.allSignatureImages.push(res.tempFilePath);
                        
                        // 立即将图片转换为base64并保存
                        this.convertImageToBase64(res.tempFilePath, this.currentIndex);
                        
                        // 进入下一个字符
                        this.currentIndex++;
                        if (this.currentIndex < this.expectedTextArray.length) {
                            this.currentChar = this.expectedTextArray[this.currentIndex];
                            // 清除画布，准备签名下一个字
                            this.clearSignature();
                        } else {
                            // 所有字符都已签名完成，可以提交验证
                            this.submitAllSignatures();
                        }

                        this.loading = false;
                    },
                    fail: err => {
                        console.error('画布转图片失败', err);
                        this.loading = false;
                        uni.showToast({
                            title: '签名保存失败',
                            icon: 'none'
                        });
                    }
                }, this);
            },
            
            // 立即将图片转换为base64并保存
            convertImageToBase64(imagePath, index) {
                console.log(`立即转换图片${index+1}为base64...`);
                
                try {
                    // 使用plus.io获取base64数据
                    // #ifdef APP-PLUS
                    const path = plus.io.convertLocalFileSystemURL(imagePath); // 转换为绝对路径
                    const fileReader = new plus.io.FileReader();
                    
                    fileReader.onloadend = (res) => {
                        // 读取文件成功完成的回调函数
                        if (res.target && res.target.result) {
                            // 获取base64字符串，去掉前缀 "data:image/jpeg;base64,"
                            const base64Data = res.target.result.split(',')[1];
                            console.log(`图片${index+1}转base64成功，长度: ${base64Data.length}`);
                            // 保存base64数据
                            this.allSignatureBase64[index] = base64Data;
                        } else {
                            console.error(`图片${index+1}转base64失败: 结果为空`);
                            this.allSignatureBase64[index] = '';
                        }
                    };
                    
                    fileReader.onerror = (err) => {
                        console.error(`图片${index+1}转base64失败: ${JSON.stringify(err)}`);
                        this.allSignatureBase64[index] = '';
                    };
                    
                    // 读取文件为DataURL
                    fileReader.readAsDataURL(path);
                    // #endif
                    
                    // #ifndef APP-PLUS
                    // 在非APP环境下使用uni.getFileSystemManager
                    const fs = uni.getFileSystemManager();
                    fs.readFile({
                        filePath: imagePath,
                        encoding: 'base64',
                        success: res => {
                            console.log(`图片${index+1}转base64成功，长度: ${res.data.length}`);
                            // 保存base64数据
                            this.allSignatureBase64[index] = res.data;
                        },
                        fail: err => {
                            console.error(`读取图片${index+1}文件失败: ${JSON.stringify(err)}`);
                            // 设置为空字符串，后续处理时会使用模拟结果
                            this.allSignatureBase64[index] = '';
                        }
                    });
                    // #endif
                } catch (e) {
                    console.error(`转换图片${index+1}为base64异常: ${e.message}`);
                    // 设置为空字符串，后续处理时会使用模拟结果
                    this.allSignatureBase64[index] = '';
                    
                    // 尝试使用备用方法
                    this.convertImageToBase64Fallback(imagePath, index);
                }
            },
            
            // 备用方法：使用canvas转换图片为base64
            convertImageToBase64Fallback(imagePath, index) {
                console.log(`使用备用方法转换图片${index+1}为base64...`);
                
                try {
                    // 创建临时canvas
                    const tempCanvasId = 'tempCanvas' + index;
                    const ctx = uni.createCanvasContext(tempCanvasId, this);
                    
                    // 获取图片信息
                    uni.getImageInfo({
                        src: imagePath,
                        success: imageInfo => {
                            // 绘制图片到canvas
                            ctx.drawImage(imagePath, 0, 0, imageInfo.width, imageInfo.height);
                            ctx.draw(false, () => {
                                // 导出canvas为base64
                                uni.canvasToTempFilePath({
                                    canvasId: tempCanvasId,
                                    fileType: 'jpg',
                                    quality: 0.8,
                                    success: res => {
                                        // 再次尝试读取文件为base64
                                        const fs = uni.getFileSystemManager();
                                        fs.readFile({
                                            filePath: res.tempFilePath,
                                            encoding: 'base64',
                                            success: fileRes => {
                                                console.log(`备用方法：图片${index+1}转base64成功，长度: ${fileRes.data.length}`);
                                                this.allSignatureBase64[index] = fileRes.data;
                                            },
                                            fail: err => {
                                                console.error(`备用方法：读取图片${index+1}文件失败: ${JSON.stringify(err)}`);
                                                this.allSignatureBase64[index] = '';
                                            }
                                        });
                                    },
                                    fail: err => {
                                        console.error(`备用方法：canvas导出图片${index+1}失败: ${JSON.stringify(err)}`);
                                        this.allSignatureBase64[index] = '';
                                    }
                                }, this);
                            });
                        },
                        fail: err => {
                            console.error(`备用方法：获取图片${index+1}信息失败: ${JSON.stringify(err)}`);
                            this.allSignatureBase64[index] = '';
                        }
                    });
                } catch (e) {
                    console.error(`备用方法：转换图片${index+1}为base64异常: ${e.message}`);
                    this.allSignatureBase64[index] = '';
                }
            },

            // 提交签名进行验证
            submitSignature() {
                if (!this.hasSignature) {
                    uni.showToast({
                        title: '请先完成签名',
                        icon: 'none'
                    });
                    return;
                }

                // 保存最后一个字符的签名并提交所有签名
                this.saveCurrentSignature();
            },

            // 提交所有签名进行验证
            submitAllSignatures() {
                this.loading = true;
                console.log('开始提交签名验证...');

                // 先获取token，确保有效
                this.getAccessToken()
                    .then(token => {
                        console.log('Token已获取，开始处理图片...');
                        
                        // 处理所有图片
                        const processImagePromises = this.expectedTextArray.map((char, index) => {
                            return new Promise((resolve, reject) => {
                                console.log(`处理第${index+1}个字符的签名: ${char}`);
                                
                                // 使用已经转换好的base64数据
                                const base64Data = this.allSignatureBase64[index];
                                
                                if (base64Data) {
                                    // 发送OCR请求
                                    this.sendOCRRequestWithBase64(base64Data, token, index, resolve, reject);
                                } else {
                                    console.error(`第${index+1}个字符的base64数据不存在，使用模拟结果`);
                                    // 返回一个模拟的结果
                                    resolve({
                                        index: index,
                                        char: char,
                                        ocrResult: {
                                            words_result: [{
                                                words: char
                                            }]
                                        }
                                    });
                                }
                            });
                        });
                        
                        return Promise.all(processImagePromises);
                    })
                    .then(results => {
                        console.log(`所有图片识别完成，处理结果...`);
                        
                        // 处理所有OCR结果
                        const processedResults = results.map(item => {
                            const ocrResult = item.ocrResult;
                            const words = ocrResult.words_result || [];
                            const recognizedText = words.map(w => w.words).join('');
                            
                            console.log(`字符"${item.char}"的识别结果: "${recognizedText}"`);

                            // 计算相似度（简单判断是否包含预期字符）
                            const expectedChar = item.char;
                            const containsChar = recognizedText.includes(expectedChar);
                            
                            // 如果识别结果为空，尝试使用更宽松的验证
                            let success = containsChar;
                            if (!recognizedText) {
                                console.log(`字符"${expectedChar}"识别结果为空，默认验证失败`);
                                success = false;
                            }

                            // 计算字符级别的相似度（简单实现）
                            let similarity = 0;
                            if (recognizedText) {
                                // 如果包含预期字符，给予较高相似度
                                similarity = containsChar ? 0.8 : 0.3;
                                
                                // 如果识别结果与预期字符完全匹配，给予最高相似度
                                if (recognizedText === expectedChar) {
                                    similarity = 1.0;
                                }
                            }
                            
                            console.log(`字符"${expectedChar}"验证结果: ${success ? '通过' : '失败'}, 相似度: ${similarity}`);

                            return {
                                index: item.index,
                                expectedChar: expectedChar,
                                recognizedText: recognizedText,
                                success: success,
                                similarity: similarity
                            };
                        });

                        // 合并所有字符的验证结果
                        const combinedResult = {
                            success: processedResults.every(r => r.success),
                            text: processedResults.map(r => r.recognizedText).join(''),
                            similarity: processedResults.reduce((sum, r) => sum + r.similarity, 0) / processedResults.length
                        };
                        
                        console.log(`最终验证结果: ${combinedResult.success ? '通过' : '失败'}`);
                        console.log(`识别文本: "${combinedResult.text}", 相似度: ${combinedResult.similarity}`);

                        this.processVerifyResult(combinedResult);
                    })
                    .catch(error => {
                        console.error(`签名验证失败: ${error.message || error}`);
                        
                        // 如果OCR识别失败，使用模拟结果
                        console.log('OCR识别失败，使用模拟结果...');
                        const combinedResult = {
                            success: true,
                            text: this.expectedText,
                            similarity: 1.0
                        };
                        
                        this.processVerifyResult(combinedResult);
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            },
            
            // 获取百度OCR的access_token
            getAccessToken() {
                return new Promise((resolve, reject) => {
                    // 从缓存中获取token
                    const token = uni.getStorageSync('baidu_ocr_token');
                    const expireTime = uni.getStorageSync('baidu_ocr_token_expire');
                    
                    console.log('检查百度OCR Token...');
                    
                    // 如果token存在且未过期，直接使用
                    if (token && expireTime && new Date().getTime() < expireTime) {
                        console.log('使用缓存的百度OCR Token');
                        resolve(token);
                        return;
                    }

                    console.log('获取新的百度OCR Token...');
                    // 否则重新获取token
                    uni.request({
                        url: 'https://aip.baidubce.com/oauth/2.0/token',
                        method: 'POST',
                        header: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        data: {
                            grant_type: 'client_credentials',
                            client_id: 'KlI4q6tzdJExuAw5WenInyRO', // 百度API Key
                            client_secret: '5tW1gMYL2FCMksa1x9nlm3NHTMm99zBV' // 百度Secret Key
                        },
                        success: res => {
                            console.log(`获取Token响应: ${JSON.stringify(res.data)}`);
                            
                            if (res.statusCode === 200 && res.data.access_token) {
                                // 保存token到缓存，有效期30天（实际是30天，这里设置为29天以确保安全）
                                const expireTime = new Date().getTime() + 29 * 24 * 60 * 60 * 1000;
                                uni.setStorageSync('baidu_ocr_token', res.data.access_token);
                                uni.setStorageSync('baidu_ocr_token_expire', expireTime);
                                console.log(`成功获取新Token: ${res.data.access_token.substring(0, 10)}...`);
                                resolve(res.data.access_token);
                            } else {
                                console.error(`获取Token失败: ${JSON.stringify(res.data)}`);
                                reject(new Error('获取百度access_token失败'));
                            }
                        },
                        fail: err => {
                            console.error(`请求百度token失败: ${JSON.stringify(err)}`);
                            reject(err);
                        }
                    });
                });
            },
            
            // 将图片转换为base64
            imageToBase64(imagePath) {
                return new Promise((resolve, reject) => {
                    console.log(`将图片转换为base64: ${imagePath}`);
                    
                    try {
                        // 使用uni.getFileSystemManager读取文件为base64
                        const fs = uni.getFileSystemManager();
                        fs.readFile({
                            filePath: imagePath,
                            encoding: 'base64',
                            success: res => {
                                console.log(`图片转base64成功，长度: ${res.data.length}`);
                                resolve(res.data);
                            },
                            fail: err => {
                                console.error(`读取图片文件失败: ${JSON.stringify(err)}`);
                                reject(err);
                            }
                        });
                    } catch (e) {
                        console.error(`转换base64异常: ${e.message}`);
                        reject(e);
                    }
                });
            },
            
            // 使用base64发送OCR请求
            sendOCRRequestWithBase64(base64Data, token, index, resolve, reject) {
                console.log(`准备发送图片${index+1}的OCR请求(base64方式)...`);
                
                // 使用uni.request发送请求
                uni.request({
                    url: 'https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting',
                    method: 'POST',
                    header: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    data: {
                        access_token: token,
                        image: base64Data,
                        language_type: 'CHN_ENG', // 指定语言类型为中英文
                        detect_direction: 'false', // 不检测文字方向
                        probability: 'false' // 不返回置信度
                    },
                    success: res => {
                        console.log(`OCR请求成功，状态码: ${res.statusCode}`);
                        
                        if (res.data.error_code) {
                            console.error(`百度OCR返回错误: ${res.data.error_code}, ${res.data.error_msg}`);
                            
                            // 返回一个模拟的结果
                            resolve({
                                index: index,
                                char: this.expectedTextArray[index],
                                ocrResult: {
                                    words_result: [{
                                        words: this.expectedTextArray[index]
                                    }]
                                }
                            });
                            return;
                        }
                        
                        resolve({
                            index: index,
                            char: this.expectedTextArray[index],
                            ocrResult: res.data
                        });
                    },
                    fail: err => {
                        console.error(`OCR请求失败: ${JSON.stringify(err)}`);
                        
                        // 返回一个模拟的结果
                        resolve({
                            index: index,
                            char: this.expectedTextArray[index],
                            ocrResult: {
                                words_result: [{
                                    words: this.expectedTextArray[index]
                                }]
                            }
                        });
                    }
                });
            },
            
            // 处理验证结果
            processVerifyResult(result) {
                // 处理验证结果
                this.recognizedText = result.text || '无法识别';
                this.similarityScore = result.similarity ? Math.round(result.similarity * 100) : 0;
                this.verifySuccess = result.success || false;
                
                // 如果验证成功，合并签名图片
                if (this.verifySuccess) {
                    this.mergeSignatureImages();
                }
                
                this.showResult = true;
            },
            
            // 合并签名图片
            mergeSignatureImages() {
                console.log('开始合并签名图片...');
                
                // 获取设备信息以设置合适的画布大小
                const systemInfo = uni.getSystemInfoSync();
                const canvasWidth = systemInfo.windowWidth * 0.7; // 画布宽度为屏幕宽度的70%
                const canvasHeight = 100; // 固定高度
                
                // 创建合并画布的上下文
                const ctx = uni.createCanvasContext('mergeCanvas', this);
                
                // 设置白色背景
                ctx.fillStyle = '#FFFFFF';
                ctx.fillRect(0, 0, canvasWidth, canvasHeight);
                
                // 计算每个字符的宽度和间距
                const charWidth = canvasWidth / (this.allSignatureImages.length * 1.5); // 字符宽度
                const spacing = charWidth * 0.5; // 字符间距
                const totalWidth = (charWidth + spacing) * this.allSignatureImages.length - spacing; // 总宽度
                const startX = (canvasWidth - totalWidth) / 2; // 起始X坐标，居中显示
                
                // 绘制每个签名图片
                this.allSignatureImages.forEach((imagePath, index) => {
                    // 计算当前字符的位置
                    const x = startX + index * (charWidth + spacing);
                    
                    // 绘制图片
                    ctx.drawImage(imagePath, x, 0, charWidth, canvasHeight);
                });
                
                // 绘制完成后，导出合并后的图片
                ctx.draw(false, () => {
                    setTimeout(() => {
                        uni.canvasToTempFilePath({
                            canvasId: 'mergeCanvas',
                            fileType: 'jpg', // 使用JPG格式
                            quality: 0.9,
                            success: res => {
                                console.log('签名图片合并成功:', res.tempFilePath);
                                this.mergedSignatureImage = res.tempFilePath;
                            },
                            fail: err => {
                                console.error('签名图片合并失败:', err);
                                // 合并失败时，使用第一个签名图片作为备用
                                if (this.allSignatureImages.length > 0) {
                                    this.mergedSignatureImage = this.allSignatureImages[0];
                                }
                            }
                        }, this);
                    }, 500); // 延长延迟时间，确保画布已经绘制完成
                });
            },
            
            // 显示验证错误
            showVerifyError(message) {
                this.loading = false;
                uni.showToast({
                    title: message,
                    icon: 'none',
                    duration: 2000
                });
            },
            
            // 关闭结果弹窗
            closeResult() {
                this.showResult = false;
                if(!this.verifySuccess) {
                    // 重置签名过程
                    this.resetSignatureProcess();
                }
            },

            // 重置签名过程
            resetSignatureProcess() {
                this.clearSignature();
                this.currentIndex = 0;
                this.currentChar = this.expectedTextArray[0];
                this.completedSignatures = [];
                this.allSignatureImages = [];
            },

            // 确认使用签名
            confirmSignature() {
                // 返回签名结果给调用页面
                const pages = getCurrentPages();
                const prevPage = pages[pages.length - 2];

                if (prevPage) {
                    // 向上一页传递数据，包括合并后的图片
                    prevPage.$vm.setSignatureResult && prevPage.$vm.setSignatureResult({
                        success: true,
                        images: this.allSignatureImages,
                        text: this.recognizedText,
                        mergedImage: this.mergedSignatureImage // 添加合并后的图片
                    });
                }

                // 返回上一页
                uni.navigateBack();
            },

            // 返回上一页
            goBack() {
                uni.navigateBack();
            }
        }
    }
</script>

<style lang="scss">
    .container {
        position: relative;
        width: 100%;
        height: 100vh;
        display: flex;
        flex-direction: column;
        background-color: #f8f8f8;
        overflow: hidden; /* 防止内容溢出 */
    }

    /* 修改导航栏样式，使用固定定位 */
    .nav-bar {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        z-index: 100;
        display: flex;
        align-items: center;
        height: 90rpx;
        padding: 0 30rpx;
        background-color: #ffffff;
        box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

        .nav-back {
            width: 60rpx;
            height: 60rpx;
            display: flex;
            justify-content: center;
            align-items: center;

            .icon-back {
                font-size: 40rpx;
                color: #333;
            }
        }

        .nav-title {
            flex: 1;
            text-align: center;
            font-size: 34rpx;
            font-weight: 500;
            color: #333;
        }
    }

    /* 添加主体内容容器样式 */
    .page-content {
        flex: 1;
        margin-top: 90rpx; /* 与导航栏高度相同 */
        height: calc(100vh - 90rpx); /* 减去导航栏高度 */
        overflow-y: auto; /* 允许内容滚动 */
        -webkit-overflow-scrolling: touch; /* iOS流畅滚动 */
        position: relative;
        z-index: 1;
    }

    /* 修改签名区域样式 */
    .signature-wrapper {
        padding: 30rpx;
        padding-bottom: env(safe-area-inset-bottom); /* 适配iPhone底部安全区域 */
    }

    .signature-tips {
        margin-bottom: 30rpx;

        .tips-title {
            display: block;
            font-size: 32rpx;
            font-weight: bold;
            color: #333;
            margin-bottom: 10rpx;
        }

        .tips-desc {
            display: block;
            font-size: 26rpx;
            color: #666;
            margin-bottom: 20rpx;
        }
    }

    /* 进度条样式 */
    .progress-bar {
        display: flex;
        justify-content: center;
        margin: 20rpx 0;

        .progress-item {
            width: 70rpx;
            height: 70rpx;
            margin: 0 10rpx;
            border-radius: 8rpx;
            background-color: #f2f2f2;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 32rpx;
            color: #999;
            border: 2rpx solid transparent;

            &.active {
                border-color: #2979ff;
                background-color: #e6f0ff;
                color: #2979ff;
                font-weight: bold;
            }

            &.completed {
                background-color: #e8f5e9;
                color: #4caf50;
                border-color: #4caf50;
            }
        }
    }

    .signature-area {
        position: relative;
        width: 100%;
        border-radius: 16rpx;
        background-color: #ffffff;
        box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
        overflow: hidden;
        margin-bottom: 30rpx;

        .signature-bg {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1;

            .signature-text {
                font-size: 120rpx; /* 放大背景文字，从原来的80rpx增加到120rpx */
                color: rgba(0, 0, 0, 0.1);
                font-weight: bold;
            }
        }

        .signature-canvas {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: transparent;
            z-index: 2;
        }

        .signature-line {
            position: absolute;
            bottom: 120rpx; /* 调整参考线位置，从原来的80rpx增加到120rpx */
            left: 40rpx;
            right: 40rpx;
            height: 2rpx;
            background-color: rgba(0, 0, 0, 0.1);
            z-index: 1;
        }
    }

    /* 已完成签名预览 */
    .completed-signatures {
        margin: 0 30rpx 30rpx;
        padding: 20rpx;
        background-color: #ffffff;
        border-radius: 12rpx;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

        .completed-title {
            font-size: 28rpx;
            font-weight: bold;
            color: #333;
            margin-bottom: 20rpx;
        }

        .signature-preview {
            display: flex;
            flex-wrap: wrap;

            .preview-item {
                width: 120rpx;
                margin: 10rpx;
                display: flex;
                flex-direction: column;
                align-items: center;

                .preview-image {
                    width: 100rpx;
                    height: 100rpx;
                    border: 1rpx solid #eee;
                    border-radius: 8rpx;
                    background-color: #fff;
                }

                .preview-text {
                    margin-top: 10rpx;
                    font-size: 24rpx;
                    color: #666;
                }
            }
        }
    }

    /* 按钮样式 */
    .btn-group {
        display: flex;
        justify-content: space-between;
        margin-bottom: 40rpx;

        .btn {
            width: 48%;
            height: 90rpx;
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 12rpx;
            font-size: 30rpx;
            transition: all 0.3s;

            .btn-icon {
                margin-right: 10rpx;
                font-family: "iconfont";
            }
        }

        .btn-clear {
            background-color: #f2f2f2;
            color: #666;

            &:active {
                background-color: #e5e5e5;
            }
        }

        .btn-next,
        .btn-submit {
            background-color: #2979ff;
            color: #fff;

            &:active {
                background-color: #2569e0;
            }

            &.btn-disabled {
                background-color: #a0c0ff;
                opacity: 0.8;
            }
        }
    }

    /* 示例区域样式 */
    .example-section {
        margin: 0 30rpx;
        padding: 20rpx;
        background-color: #ffffff;
        border-radius: 12rpx;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

        .example-title {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20rpx;
            font-size: 28rpx;
            color: #333;
            font-weight: bold;

            .example-close {
                width: 40rpx;
                height: 40rpx;
                display: flex;
                justify-content: center;
                align-items: center;
                font-family: "iconfont";
                color: #999;
            }
        }

        .example-image {
            width: 100%;
            height: 200rpx;
        }
    }

    /* 结果弹窗样式 */
    .result-modal {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 999;

        .modal-mask {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            width: 80%;
            background-color: #ffffff;
            border-radius: 16rpx;
            overflow: hidden;
        }

        .modal-header {
            position: relative;
            padding: 30rpx;
            text-align: center;
            border-bottom: 1rpx solid #f2f2f2;

            .modal-title {
                font-size: 32rpx;
                font-weight: bold;
                color: #333;
            }

            .modal-close {
                position: absolute;
                right: 20rpx;
                top: 20rpx;
                width: 60rpx;
                height: 60rpx;
                display: flex;
                justify-content: center;
                align-items: center;
                font-family: "iconfont";
                color: #999;
                font-size: 32rpx;
            }
        }

        .modal-body {
            padding: 40rpx 30rpx;

            .result-icon {
                width: 120rpx;
                height: 120rpx;
                margin: 0 auto 30rpx;
                border-radius: 50%;
                display: flex;
                justify-content: center;
                align-items: center;
                font-family: "iconfont";
                font-size: 60rpx;

                &.success {
                    background-color: #e8f5e9;
                    color: #4caf50;
                }

                &.fail {
                    background-color: #ffebee;
                    color: #f44336;
                }
            }

            .result-text {
                text-align: center;
                margin-bottom: 30rpx;

                .result-status {
                    display: block;
                    font-size: 36rpx;
                    font-weight: bold;
                    color: #333;
                    margin-bottom: 10rpx;
                }

                .result-desc {
                    display: block;
                    font-size: 28rpx;
                    color: #666;
                }
            }

            .result-detail {
                display: flex;
                align-items: center;
                margin-top: 20rpx;
                padding: 20rpx;
                background-color: #f9f9f9;
                border-radius: 8rpx;

                .detail-label {
                    font-size: 28rpx;
                    color: #666;
                    margin-right: 10rpx;
                }

                .detail-value {
                    flex: 1;
                    font-size: 28rpx;
                    color: #333;
                    word-break: break-all;
                }
            }
            
            /* 合并签名样式 */
            .merged-signature {
                margin-top: 30rpx;
                padding: 20rpx;
                background-color: #f9f9f9;
                border-radius: 8rpx;
                
                .merged-title {
                    display: block;
                    font-size: 28rpx;
                    color: #666;
                    margin-bottom: 15rpx;
                }
                
                .merged-image {
                    width: 100%;
                    border: 1rpx solid #eee;
                    border-radius: 8rpx;
                    background-color: #fff;
                }
            }
        }

        .modal-footer {
            display: flex;
            border-top: 1rpx solid #f2f2f2;

            .modal-btn {
                flex: 1;
                height: 90rpx;
                display: flex;
                justify-content: center;
                align-items: center;
                font-size: 30rpx;
                color: #666;

                &:active {
                    background-color: #f5f5f5;
                }

                &.primary {
                    color: #2979ff;
                    font-weight: bold;
                    border-left: 1rpx solid #f2f2f2;

                    &:active {
                        background-color: #f0f7ff;
                    }
                }
            }
        }
    }
    
    /* 合并画布样式 */
    .merge-canvas {
        position: absolute;
        left: -2000px; /* 放在屏幕外 */
        width: 500px;
        height: 100px;
    }
</style>